﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Diagnostics;
using TESTCommons.Encrypt;
using TESTCommons.HttpHelper;
using TESTCommons.JsonHelper;
using TestManage.Infrastructure.CustomAttribute;
using TestManage.Models;
using TestModel.SysManage;
using TestService.SysManage;

namespace TestManage.Controllers
{
    [AopActionFilter(true, false)]
    public class HomeController : BaseController
    {
        #region 参数
        private readonly ISys_UserService _sys_UserService;
        private readonly ISys_RoleMenuFunctionService _sys_RoleMenuFunctionService;
        #endregion

        #region 构造函数
        public HomeController(ISys_UserService sys_UserService,
            ISys_RoleMenuFunctionService sys_RoleMenuFunctionService)
        {
            _sys_UserService = sys_UserService;
            _sys_RoleMenuFunctionService = sys_RoleMenuFunctionService;
        }
        #endregion

        protected override void Init()
        {
            base.Init();
        }

        public override IActionResult Index()
        {
            return View(this._account);
        }

        /// <summary>
        /// 默认主页
        /// </summary>
        [HttpGet]
        public ActionResult Default()
        {
            return View();
        }

        /// <summary>
        /// 查看图标
        /// </summary>
        [HttpGet]
        public ActionResult LookIcon()
        {
            return View();
        }

        [HttpGet]
        public JsonResult GetList()
        {
            var account = this._account;
            return Json(_sys_RoleMenuFunctionService.GetUserMenu(account.IsSuperManage, account.RoleIDs));
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        [HttpGet]
        public ActionResult UserPullOut()
        {
            WebHelper.SetSession("session_account", null);
            return Redirect("~/Login/Index");
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        [HttpPost]
        public ActionResult UpdatePwd(sys_User model)
        {
            var user = _sys_UserService.GetModel(_account.UserID);
            if (user.userPwd != MD5Provider.Hash(model.oldPwd))
            {
                return Json(new AjaxResult { type = ResultType.error, message = "原密码错误" });
            }
            user.userPwd = MD5Provider.Hash(model.userPwd);
            user.finallyTime = DateTime.Now;
            _sys_UserService.UpdateUser(user);
            return Json(new AjaxResult { type = ResultType.success, message = "修改成功" });
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
